<template>
  <div class="comment-list-container">
    <h3>评论 ({{ totalCommentsCount }})</h3>
    
    <!-- 评论输入区域 -->
    <div v-if="userStore.isLoggedIn" class="comment-input-section">
      <a-avatar :src="userStore.userInfo?.avatar" :size="40">
        {{ userStore.userInfo?.nickname?.charAt(0) || 'U' }}
      </a-avatar>
      <div class="comment-input-wrapper">
        <a-textarea
          v-model:value="commentContent"
          placeholder="写下你的评论..."
          :rows="3"
          class="comment-textarea"
        />
        <div class="comment-actions">
          <a-button 
            type="primary" 
            @click="submitComment"
            :loading="submitting"
            :disabled="!commentContent.trim() || !postId"
          >
            发表评论
          </a-button>
        </div>
      </div>
    </div>
    
    <div v-else class="login-prompt">
      <p>请 <a @click="$router.push('/login')">登录</a> 后发表评论，登录后可享受更多互动功能</p>
    </div>
    
    <!-- 评论列表 -->
    <div class="comments-list">
      <div 
        v-for="comment in comments" 
        :key="comment.id"
        class="comment-item"
      >
        <!-- 顶级评论 -->
        <div class="comment-main">
          <a-avatar :src="comment.author?.avatar" :size="40">
            {{ comment.author?.nickname?.charAt(0) || 'U' }}
          </a-avatar>
          <div class="comment-content">
            <div class="comment-header">
              <span class="comment-author">{{ comment.author?.nickname || '匿名用户' }}</span>
              <span class="comment-date">{{ formatDate(comment.createdAt) }}</span>
            </div>
            <div class="comment-text">
              {{ comment.content }}
            </div>
            <div class="comment-footer">
              <a-button type="text" size="small" @click="handleLikeComment(comment)">
                <template #icon>
                  <LikeOutlined :style="{ color: isLiked(comment.id) ? '#1890ff' : undefined }" />
                </template>
                {{ comment.likeCount || 0 }}
              </a-button>
              <a-button type="text" size="small" @click="startReplyTo(comment)">
                回复
              </a-button>
            </div>
          </div>
        </div>
        
        <!-- 回复评论的输入区域 -->
        <div v-if="replyingToCommentId === comment.id" class="reply-input-section">
          <a-avatar :src="userStore.userInfo?.avatar" :size="32">
            {{ userStore.userInfo?.nickname?.charAt(0) || 'U' }}
          </a-avatar>
          <div class="reply-input-wrapper">
            <a-textarea
              v-model:value="replyContent"
              :placeholder="`回复 ${comment.author?.nickname || '匿名用户'}:`"
              :rows="2"
              class="reply-textarea"
            />
            <div class="reply-actions">
              <a-button size="small" @click="cancelReply">取消</a-button>
              <a-button 
                type="primary" 
                size="small"
                @click="() => submitReply(comment)"
                :loading="submitting"
                :disabled="!replyContent.trim() || !postId"
              >
                发表回复
              </a-button>
            </div>
          </div>
        </div>
        
        <!-- 子评论列表 -->
        <div v-if="comment.children && comment.children.length > 0" class="sub-comments">
          <div 
            v-for="subComment in comment.children" 
            :key="subComment.id"
            class="sub-comment-item"
          >
            <a-avatar :src="subComment.author?.avatar" :size="32">
              {{ subComment.author?.nickname?.charAt(0) || 'U' }}
            </a-avatar>
            <div class="sub-comment-content">
              <div class="sub-comment-header">
                <span class="sub-comment-author">{{ subComment.author?.nickname || '匿名用户' }}</span>
                <span class="sub-comment-date">{{ formatDate(subComment.createdAt) }}</span>
              </div>
              <div class="sub-comment-text">
                {{ subComment.content }}
              </div>
              <div class="sub-comment-footer">
                <a-button type="text" size="small" @click="() => startReplyTo(subComment)">
                  回复
                </a-button>
                <a-button type="text" size="small" @click="() => handleLikeComment(subComment)">
                  <template #icon>
                    <LikeOutlined :style="{ color: isLiked(subComment.id) ? '#1890ff' : undefined }" />
                  </template>
                  {{ subComment.likeCount || 0 }}
                </a-button>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div v-if="comments.length === 0" class="no-comments">
        <a-empty description="暂无评论，快来发表第一条评论吧！" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import { LikeOutlined } from '@ant-design/icons-vue'
import { useUserStore } from '@/stores'
import { commentApi, likeApi } from '@/api'
import type { Comment } from '@/types'

const props = defineProps<{
  postId: number
}>()

const router = useRouter()
const userStore = useUserStore()
const comments = ref<Comment[]>([])
const commentContent = ref('')
const replyContent = ref('')
const submitting = ref(false)
const likedComments = ref<Set<number>>(new Set())
const replyingToCommentId = ref<number | null>(null)

// 检查postId是否有效
const isValidPostId = computed(() => {
  return props.postId && !isNaN(props.postId)
})

// 计算总评论数（包括子评论）
const totalCommentsCount = computed(() => {
  let count = comments.value.length
  comments.value.forEach(comment => {
    if (comment.children) {
      count += comment.children.length
    }
  })
  return count
})

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'short',
    day: 'numeric'
  })
}

// 提交评论
const submitComment = async () => {
  if (!commentContent.value.trim() || !isValidPostId.value) {
    return
  }
  
  try {
    submitting.value = true
    await commentApi.createComment({
      content: commentContent.value,
      postId: props.postId,
      parentId: 0 // 顶级评论
    })
    
    message.success('评论发表成功')
    commentContent.value = ''
    loadComments()
  } catch (error: any) {
    console.error('评论发表失败:', error)
    // 检查是否是文章不存在的错误
    if (error?.response?.data?.message?.includes('评论的文章不存在')) {
      message.error('文章不存在，无法发表评论')
    } else {
      message.error('评论发表失败')
    }
  } finally {
    submitting.value = false
  }
}

// 开始回复评论
const startReplyTo = (comment: Comment) => {
  if (!userStore.isLoggedIn) {
    // 用户未登录，显示登录提示
    Modal.confirm({
      title: '需要登录',
      content: '登录后才能回复评论，是否前往登录？',
      okText: '去登录',
      cancelText: '取消',
      onOk() {
        // 使用Vue Router跳转到登录页面
        router.push('/login')
      }
    })
    return
  }
  
  if (!isValidPostId.value) {
    message.error('文章不存在，无法回复评论')
    return
  }
  
  replyingToCommentId.value = comment.id
  replyContent.value = ''
}

// 取消回复
const cancelReply = () => {
  replyingToCommentId.value = null
  replyContent.value = ''
}

// 提交回复
const submitReply = async (parentComment: Comment) => {
  if (!replyContent.value.trim() || !isValidPostId.value) {
    return
  }
  
  try {
    submitting.value = true
    await commentApi.createComment({
      content: replyContent.value,
      postId: props.postId,
      parentId: parentComment.id
    })
    
    message.success('回复发表成功')
    replyingToCommentId.value = null
    replyContent.value = ''
    loadComments()
  } catch (error: any) {
    console.error('回复发表失败:', error)
    // 检查是否是文章不存在的错误
    if (error?.response?.data?.message?.includes('评论的文章不存在')) {
      message.error('文章不存在，无法发表回复')
    } else {
      message.error('回复发表失败')
    }
  } finally {
    submitting.value = false
  }
}

// 处理评论点赞
const handleLikeComment = (comment: Comment) => {
  if (!userStore.isLoggedIn) {
    // 用户未登录，显示登录提示
    Modal.confirm({
      title: '需要登录',
      content: '登录后才能点赞评论，是否前往登录？',
      okText: '去登录',
      cancelText: '取消',
      onOk() {
        // 使用Vue Router跳转到登录页面
        router.push('/login')
      }
    })
    return
  }
  
  // 用户已登录，执行点赞操作
  likeComment(comment)
}

// 点赞评论
const likeComment = async (comment: Comment) => {
  try {
    const response = await likeApi.toggleLike({
      targetType: 'COMMENT',
      targetId: comment.id
    })
    
    console.log('评论点赞操作响应:', response)
    
    // 重新加载评论以确保点赞数准确
    await loadComments()
    
    // 根据响应消息显示合适的提示
    if (response.message.includes('取消')) {
      message.success('取消点赞成功')
    } else {
      message.success('点赞成功')
    }
  } catch (error) {
    console.error('评论点赞操作失败:', error)
    message.error('操作失败')
  }
}

// 更新评论点赞数（包括子评论）
const updateCommentLikeCount = (commentsList: Comment[], commentId: number, likeCount: number) => {
  for (const comment of commentsList) {
    if (comment.id === commentId) {
      comment.likeCount = likeCount
      return true
    }
    if (comment.children) {
      if (updateCommentLikeCount(comment.children, commentId, likeCount)) {
        return true
      }
    }
  }
  return false
}

// 检查是否已点赞
const isLiked = (commentId: number) => {
  return likedComments.value.has(commentId)
}

// 加载评论
const loadComments = async () => {
  // 检查postId是否有效
  if (!isValidPostId.value) {
    comments.value = []
    return
  }
  
  try {
    const response = await commentApi.getCommentTree(props.postId)
    console.log('评论树数据响应:', response)
    comments.value = response.data || []
  } catch (error: any) {
    console.error('加载评论失败:', error)
    comments.value = []
    // 检查是否是文章不存在的错误
    if (error?.response?.data?.message?.includes('评论的文章不存在')) {
      // 不显示错误消息，因为这可能是预期行为（文章被删除等）
      console.log('文章不存在，无法加载评论')
    } else {
      message.error('加载评论失败')
    }
  }
}

// 监听postId变化
watch(() => props.postId, (newPostId) => {
  if (newPostId && !isNaN(newPostId)) {
    loadComments()
  } else {
    comments.value = []
  }
})

onMounted(() => {
  loadComments()
})
</script>

<style scoped>
.comment-list-container {
  margin-top: 40px;
  padding: 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.comment-list-container h3 {
  margin: 0 0 24px 0;
  font-size: 20px;
  font-weight: 600;
  color: #262626;
}

.comment-input-section,
.reply-input-section {
  display: flex;
  gap: 16px;
  margin-bottom: 32px;
}

.comment-input-wrapper,
.reply-input-wrapper {
  flex: 1;
}

.comment-textarea,
.reply-textarea {
  margin-bottom: 12px;
}

.comment-actions,
.reply-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.login-prompt {
  text-align: center;
  padding: 24px;
  background: #f5f5f5;
  border-radius: 8px;
  margin-bottom: 32px;
}

.login-prompt a {
  color: #1890ff;
  cursor: pointer;
  text-decoration: underline;
}

.comment-item {
  padding: 24px 0;
  border-bottom: 1px solid #f0f0f0;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-main {
  display: flex;
  gap: 16px;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.comment-author {
  font-weight: 600;
  color: #262626;
}

.comment-date {
  font-size: 12px;
  color: #8c8c8c;
}

.comment-text {
  margin-bottom: 16px;
  line-height: 1.6;
  color: #595959;
}

.comment-footer {
  display: flex;
  gap: 16px;
}

.reply-input-section {
  margin-top: 16px;
  padding-left: 56px;
}

.sub-comments {
  margin-top: 16px;
  padding-left: 56px;
}

.sub-comment-item {
  display: flex;
  gap: 12px;
  padding: 12px 0;
  border-bottom: 1px dashed #f0f0f0;
}

.sub-comment-item:last-child {
  border-bottom: none;
}

.sub-comment-content {
  flex: 1;
}

.sub-comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
}

.sub-comment-author {
  font-weight: 500;
  color: #595959;
  font-size: 13px;
}

.sub-comment-date {
  font-size: 11px;
  color: #bfbfbf;
}

.sub-comment-text {
  margin-bottom: 8px;
  line-height: 1.5;
  color: #595959;
  font-size: 13px;
}

.sub-comment-footer {
  display: flex;
  gap: 12px;
}

.no-comments {
  text-align: center;
  padding: 40px 0;
}
</style>